package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmProcessService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WmProcessService wmProcessService;



    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1.非空判断
        dto.checkParam();
        //2.分页查询
        IPage<WmNews> page=new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper= Wrappers.lambdaQuery();
        //2.1 根据状态查询
        if(dto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        //2.2 根据关键字查询
        if(!StringUtils.isEmpty(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        //2.3 根据频道id查询
        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        //2.4 根据开始和结束时间查询
        if(dto.getBeginPubdate()!=null && dto.getEndPubdate()!=null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubdate(),dto.getEndPubdate());
        }

        //2.5 根据登录用户id查询
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        page=super.page(page,queryWrapper);

        //3.返回数据结果
        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 保存-修改-提交草稿为一体的方法
     *  主方法
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //TODO
        //1.是否存在id
        WmNews wmNews = new WmNews();
        Integer id = dto.getId();
        if(dto.getId()!=null){
             wmNews = this.lambdaQuery().eq(WmNews::getId, dto.getId()).one();
        }
        // 解析最外层 JSON 对象
        String content = dto.getContent();
        // 获取 "content" 对应的 JSON 数组
        JSONArray contentArray = JSONArray.parseArray(content);
        //获取内容中图片数量已经url
        List<String> image = new ArrayList<>();
        int imageCount = 0;
        for (int i = 0; i < contentArray.size(); i++) {
            JSONObject itemObj = contentArray.getJSONObject(i);
            String type = itemObj.getString("type");
            if ("image".equals(type)) {
                imageCount++;
                String imageValue = itemObj.getString("value");
                image.add(imageValue);
            }
        }

        if(wmNews.getId()==null){
            //新增文章
            BeanUtils.copyProperties(dto,wmNews);
            List<String> images = dto.getImages();
            wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
            wmNews.setImages(StringUtils.join(images,","));
            wmNews.setCreatedTime(LocalDateTime.now());
        }else{
            //2.删除已关联的素材关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //删除旧的文章
            this.removeById(dto.getId());
            //3.修改文章对象
            List<String> images = dto.getImages();
            wmNews.setImages(StringUtils.join(images,","));
            wmNews.setContent(dto.getContent());
            wmNews.setEnable(dto.getEnable());
            wmNews.setTitle(dto.getTitle());
            wmNews.setChannelId(dto.getChannelId());
            wmNews.setType(dto.getType());
            wmNews.setSubmitedTime(dto.getSubmitedTime());
            wmNews.setStatus(dto.getStatus());
        }
        //判断是否自动选择封面图片
        if(wmNews.getType()<0){
            if(imageCount==0){
                wmNews.setImages(null);
                wmNews.setType((short) 0);
            } else if (imageCount>=1&&imageCount<3) {
                //随机在image的List集合中选择一个地址
                wmNews.setImages(image.get(0));
                wmNews.setType((short) 1);
            }else if(imageCount>=3){
                //拼接三个字符串
                wmNews.setImages(image.get(0)+","+image.get(1)+","+image.get(2));
                wmNews.setType((short) 3);
            }
        }
        //保存文章
        boolean result = this.save(wmNews);
        if(!result){
            return ResponseResult.errorResult(2,"保存文章失败");
        }
        //4.判断是否为草稿
        if(dto.getStatus()!=0){
            List<Integer> ids = new ArrayList<>();
            //保存图片到素材信息表
            image.forEach(x->{
                Integer i = wmMaterialMapper.selectCount(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUrl, x));
                if(i==0){
                    WmMaterial wmMaterial = new WmMaterial();
                    wmMaterial.setType((short) 0);
                    wmMaterial.setUrl(x);
                    wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
                    wmMaterial.setIsCollection((short) 0);
                    wmMaterial.setCreatedTime(LocalDateTime.now());
                    wmMaterialMapper.insert(wmMaterial);
                    ids.add(wmMaterial.getId());
                }
            });
            //5.关联图片与文章的关系
            ids.forEach(a->{
                WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
                wmNewsMaterial.setMaterialId(a);
                wmNewsMaterial.setNewsId(dto.getId());
                wmNewsMaterial.setType((short) 0);
                wmNewsMaterialMapper.insert(wmNewsMaterial);
            });
        }
        //自动审核文章和图片
        wmProcessService.ProcessContent(wmNews.getId());
        //6.返回数据
        return ResponseResult.okResult("发布文章完成");
    }

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
       //TODO
        //根据id查询文章
        if(dto.getId()==null){
            return new ResponseResult().error(501, "文章Id不可缺少");
        }
        WmNews wmNews = this.getById(dto.getId());
        if(wmNews==null){
            return new ResponseResult().error(1002, "文章不存在");
        }
        if(wmNews.getStatus()!=9){
            return new ResponseResult().error(501, "当前文章不是发布状态");
        }
        boolean result = this.update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, dto.getEnable()));
        if(!result){
            throw new RuntimeException("文章上下架状态修改失败");
        }

        Map<String,Object> map = new HashMap<>();
        map.put("articled", wmNews.getArticleId());
        map.put("enable", dto.getEnable());
        rabbitTemplate.convertAndSend(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_ROUTINGKEY,map);
        return ResponseResult.okResult("文章上下架完成");
    }

    @Override
    public ResponseResult selectOne(Long id) {
        WmNewsDto dto = new WmNewsDto();
        WmNews wmNews = this.getById(id);
        BeanUtils.copyProperties(wmNews, dto);
        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));

        //使用stream流获取wmMaterial中的url属性返回一个List<String>集合
        List<String> images = wmNewsMaterials.stream().map(x -> {
            WmMaterial wmMaterial = wmMaterialMapper.selectById(x.getMaterialId());
            return wmMaterial.getUrl();
        }).collect(Collectors.toList());

        dto.setImages(images);
        return ResponseResult.okResult(dto);
    }
}
